package com.csw.android.dev_utils.ex

import android.app.Activity
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.csw.android.dev_utils.ui.CommonActivity

object ActivityEx {

    /**
     * 绑定ViewModel
     */
    inline fun <reified V : ViewModel> ComponentActivity.bindVM(): V {
        return get(V::class.java)
    }

    /**
     * 绑定ViewModel
     */
    fun <V : ViewModel> ComponentActivity.bindVM(clazz: Class<V>): V {
        return get(clazz)
    }

    /**
     * 通过通用Activity打开Fragment
     */
    inline fun <reified V : Fragment> Activity.openInCommonActivity(data: Bundle? = null) {
        CommonActivity.openActivity(this, V::class.java, data)
    }

    /**
     * 通过通用Activity打开Fragment
     */
    fun <T : Fragment> Activity.openInCommonActivity(
        fragmentClass: Class<T>,
        data: Bundle? = null
    ) {
        CommonActivity.openActivity(this, fragmentClass, data)
    }

    /**
     * 判断是否所有权限都授予了
     *
     * @param finalActivity 上下文
     * @param permissions 所有要检查的权限
     */
    fun Activity.isAllPermissionGranted(
        vararg permissions: String
    ): Boolean {
        permissions.forEach { permission ->
            if (
                ActivityCompat.checkSelfPermission(
                    this,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return false
            }
        }
        return true
    }

}